import UserModel from "../db/model/user.model";
import OrganizationModel from "../db/model/organization.model";
import { tokenkeydom, APP_PRIVATE_KEY, APP_PUBLIC_KEY, saltrandom } from "../setting";
import RSA from 'node-rsa'
import md5 = require("md5");
import { Op } from 'sequelize'
import MemberModel from "../db/model/member.model";

const PRIVATE_KEY = new RSA(APP_PRIVATE_KEY)
const PUBLIC_KEY = new RSA(APP_PUBLIC_KEY)

/**
 * 注册
 * 
 * @param userPhone 
 * @param userPass 
 * @param userStuId 
 * @param userSex 
 * 
 * @returns token
 */
export async function userRegister(userPhone: string, userPass: string, userStuId: string, userSex: number = 1): Promise<string> {
    let usercount = await UserModel.count({
        where: {
            [Op.or]: {
                userPhone: userPhone,
                userStuId: userStuId
            }
        }
    })
    if (usercount > 0)
        return null
    let salt = saltrandom()
    let data = tokenkeydom()
    let user = await UserModel.create({
        userPhone: userPhone,
        userPass: md5(`${userPass}:${salt}`),
        userStuId: userStuId,
        userSex: userSex,
        tokenKey: data,
        salt: salt,
        tokenOverTime: new Date(Date.now() + 10 * 60 * 1000)
    })
    let token = PUBLIC_KEY.encrypt(JSON.stringify({
        userId: user.userId,
        token: data
    }), 'base64')
    return token
}

/**
 * 登陆
 * 
 * @param userPhone 
 * @param userPass
 * 
 * @returns token 
 */
export async function userLogin(userPhone: string, userPass: string): Promise<string> {
    let user = await UserModel.findOne({
        where: {
            userPhone: userPhone
        }
    })
    if (user == null) {
        return null
    }
    if (user.userPass !== md5(`${userPass}:${user.salt}`)) {
        return null
    }
    let data = tokenkeydom()
    user.tokenKey = data
    user.tokenOverTime = new Date(Date.now() + 10 * 60 * 1000)
    await user.save()
    let token = PUBLIC_KEY.encrypt(JSON.stringify({
        userId: user.userId,
        token: data
    }), 'base64')
    return token
}

/**
 * 换取用户信息
 * @param token 密钥
 */
export async function userStatue(token: string): Promise<UserModel> {
    let tokenData = JSON.parse(PRIVATE_KEY.decrypt(token, 'utf8'))
    let user = await UserModel.findOne({
        where: {
            userId: tokenData['userId'],
            tokenOverTime: {
                [Op.gte]: new Date()
            }
        }
    })
    if (user == null)
        return null
    if (user.tokenKey != tokenData['token'])
        return null
    else return user
}

/**
 * 获得社团列表
 */
export async function orgainizationList(page: number = 1, pageSize: number = 10): Promise<OrganizationModel[]> {
    return await OrganizationModel.findAll({
        offset: (page - 1) * pageSize,
        limit: pageSize
    })
}

/**
 * 社团详情
 * 
 * @param organizationId 
 */
export async function organizationDetial(organizationId: number): Promise<OrganizationModel> {
    return await OrganizationModel.findByPk(organizationId)
}

/**
 * 申请加入社团
 * 
 * @param organizationId 
 * @param token 
 * @param joinForm 
 * 
 * @returns 是否成功
 */
export async function joinIn(organizationId: number, token: string, joinForm: string): Promise<boolean> {
    let user = await userStatue(token)
    if (user == null)
        throw new Error('LOGIN_TIME_OUT')
    if ((await MemberModel.count({ where: { userId: user.userId, organizationId: organizationId, statue: { $not: -1 } } })) > 0) {
        return false
    }
    let member = new MemberModel()
    member.organizationId = organizationId
    member.userId = user.userId
    member.statue = 0;
    member.joinForm = joinForm;
    member.save()
    return true
}